<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>A4LIFE</title>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="./plugin/css/layui.css">
    <style lang="less">
        *{ margin: 0 ;padding: 0;user-select: none;}
        a{text-decoration: none;outline: none;}
        .a4{background-color: #eee;background-size: cover;min-height: 100vh;}
        .a4_cont{width: 1200px;margin: 0 auto;background-color: #eee;}
        .a4_cont *{box-sizing: border-box;}

        .a4_nav{padding: 30px 40px 20px 20px;}
        .a4_nav>h2{display: inline-block;color: #1e90ff;margin-right: 30px;font-size: 30px;}
        .a4_nav>a{display: inline-block;color: #666;margin-right: 10px;line-height: 34px;}
        .a4_nav>a:hover{color: #1e90ff;cursor: pointer;}
        .a4_nav>.a4_nav_active{color: #1e90ff;}
        .a4_desc{display: none;line-height: 34px;font-size: 14px;color: #333;}

        .a4_left{display: inline-block;vertical-align: middle;}
        .a4_left_item{height: 25px;text-align: center;padding: 0 10px;color: #666;font-size: 12px;margin-bottom: 5px;line-height: 25px;}
        .a4_left_item:last-child{margin-bottom: 0;}

        .a4_body{width: calc( 1160px - 60px );display: inline-block;vertical-align: middle;}
        
        .a4_head{}
        .a4_head_item{width: 25px;height: 25px;text-align: center;display: inline-block;color: #666;font-size: 13px;margin: 0 2.5px;}


        .a4_list{font-size: 0;}
        .a4_item{width: 25px;height: 25px;display: inline-block;margin: 2.5px;background-color: #ccc;cursor: pointer;}
        .a4_list>.a4_item_hover{background-color: #1e90ff;position: relative;z-index: 1;}
        .a4_alive{background-color: #fff;}
        .a4_child{background-color: #b2d09d;}
        .a4_school{background-color: #b9de71;}
        .a4_job{background-color: #7bc785;}
        .a4_spec{background-color: #80deea;}

        .popup{display: none;}

        .a4_nav_right{float: right;}
    </style>
</head>
<body>
<div class="a4">
    <div class="a4_cont">
        <div class="a4_nav">
            <h2>A4LIFE</h2>
            <!-- <a class="a4_nav_active" href="/">首页</a> -->
            <a class="a4_nav_right export">导出</a>
            <a class="a4_nav_right edit">编辑</a>
            <p class="a4_desc a4_nav_right"></p>
        </div>
        <div class="a4_left">
            <!--  -->
        </div>
        <div class="a4_body">
            <div class="a4_head">
                <!--  -->
            </div>
            <div class="a4_list">
                <!--  -->
            </div>
        </div>
    </div>
</div>    
<div class="popup">
    <form class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">出生年月</label>
            <div class="layui-input-inline">
                <input type="text" id="birth" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">入学年月</label>
            <div class="layui-input-inline">
                <input type="text" id="school" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">入职年月</label>
            <div class="layui-input-inline">
                <input type="text" id="job" class="layui-input">
            </div>
        </div>
        <button type="button" class="layui-btn layui-btn-fluid layui-bg-blue confirm">确认</button>
    </form>
</div>
<div id="export" style="display: none;">
    <!--  -->
</div>
<script src="plugin/jquery.min.js"></script>
<script src="plugin/layui.all.js"></script>
<script src="plugin/html2canvas.min.js"></script>
<script src="plugin/anime.min.js"></script>
<script>
$(function(){
    const AGE = 78;
    let a4 = {
        birth: { year: 1995,month: 5 },
        school: { year: 2002, month: 9 },
        job: { year: 2017, month: 8 },
    }

    if(!layui.data('a4')['data']){
        layui.data('a4', {
            key: 'data', value: JSON.stringify(a4)
        });
    }else{
        a4 = JSON.parse(layui.data('a4')['data'])
    }
    

    
    $('.edit').click(()=>{
        layer.open({
            type: 1,
            title: '编辑',
            shadeClose: true,
            content: $('.popup') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
        });
    });
    $('.confirm').click(()=>{
        if(!a4.birth.year){
            layer.msg('老铁，不能接受没有出生日期的人类哦');
        }else if (!a4.school.year) {
            layer.msg('老哥，你还没上学，谁信啊~');
        }else if (a4.birth.year > a4.school.year || (a4.birth.year === a4.school.year && a4.birth.month >= a4.school.month)) {
            layer.msg('老板，你是先上学再出生的？？？');
        }else if(a4.school.year > a4.job.year || (a4.school.year === a4.job.year && a4.school.month >= a4.job.month)){
            layer.msg('帅哥，你是先就职再入学的？？？');
        }else{
            layui.data('a4', {
                key: 'data', value: JSON.stringify(a4)
            });
            writeAll(a4);
            layer.closeAll(); //疯狂模式，关闭所有层
        }
    })

    let laydate = layui.laydate;
    laydate.render({ elem: '#birth', value: a4.birth.year+'-'+ padZero(a4.birth.month,2),btns: ['confirm'], type: 'month', format: 'yyyy-MM', max: 0 , done: function (value, date) {
        // console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
        a4.birth = date;
    }});
    laydate.render({ elem: '#school', value: a4.school.year + '-' + padZero(a4.school.month,2),btns: ['confirm'], type: 'month', format: 'yyyy-MM', max: 0 , done: function (value, date) {
        // console.log(date);
        a4.school = date;
    }});
    laydate.render({ elem: '#job', value: a4.job.year+'-'+ padZero(a4.job.month,2), type: 'month', format: 'yyyy-MM', max: 0 , done: function (value, date) {
        // console.log(date);
        a4.job = date;
    }});

    $('.a4_list').on('mouseenter', '.a4_item', function () {
        let $this = $(this),
            ind = $this.index(),
            x = ind % 36 + 1,
            y = Math.floor(ind / 36);
        $this.addClass('a4_item_hover')

        anime({
            targets: $('.a4_left_item:nth-child('+( y+2 )+')')[0],
            scale: 1.5,
            color: '#1e90ff'
        });
        anime({
            targets: $('.a4_head_item:nth-child('+ x +')')[0],
            scale: 1.5,
            color: '#1e90ff'
        });
        
        
    })

    $('.a4_list').on('click','.a4_item',function(){
        let $this = $(this),
            msg = $this.attr('data-spec'),
            info = $this.attr('data-inf'),
            sta = $this.hasClass('a4_job') ? ' 毒打从未停止':
                $this.hasClass('a4_school')? ' 德智体美劳的道路上奋勇直前' : 
                $this.hasClass('a4_child') ? ' 我还是个孩子' : 
                $this.hasClass('a4_alive') ? ' 未来生未来未至' : ' 地球在转';
        // console.log(sta)
        layer.tips( msg || info+sta, $(this), {
            tips: [1, '#1e90ff'],
            time: 99000
        });
        anime({
            targets: $(this)[0],
            scale: 2,
        });
    })

    $('.a4_list').on('mouseleave', '.a4_item', function () {
        $(this).removeClass('a4_item_hover')
        //关闭所有的tips层   
        layer.closeAll('tips'); 

        anime({
            targets: $(this)[0],
            scale: 1,
        });
        let $this = $(this),
            ind = $this.index(),
            x = ind % 36 + 1,
            y = Math.floor(ind / 36);
        anime({targets: $('.a4_left_item:nth-child('+( y+2 )+')')[0],scale: 1,color: '#666'});
        anime({targets: $('.a4_head_item:nth-child('+ x +')')[0],scale: 1,color: '#666'});
    })

    function padZero(num, n) {
        return (Array(n).join(0) + num).slice(-n);
    }

    writeAll(a4);

    function writeAll(arg){
        let { birth } = arg;
        writeHead();
        writeLeft(birth.year);
        writeGrid(arg);
    }

    function writeHead() {
        const HEAD = 12 * 3;
        let headarr = Array.from(new Array(HEAD), (item, i) => i % 12 + 1 );
        
        let hd = '';
        for (var i of headarr) {
            hd += `<div class="a4_head_item">${i}</div>`;
        }
        $('.a4_head').html(hd);
    }

    function writeLeft(birth) {
        const LEFT = (AGE + 3) / 3;
        let leftarr = Array.from(new Array(LEFT),(item,i)=> birth + (i*3) )
        let lt = '<div class="a4_left_item">年\\月</div>';
        for (var i of leftarr){
            lt += `<div class="a4_left_item">${i}-${i+2}</div>`;
        }
        $('.a4_left').html(lt);
    }

    function writeGrid(arg){
        let { birth, school, job } = arg;
        const GRID = (AGE + 3) * 12;
        let arr1 = Array.from(new Array(GRID), (item, i) => {
            return { 
                year: birth.year + Math.floor(i / 12),
                month: i % 12 + 1,
            }   
        })
        let html = '';
        for(var i of arr1){
            let isAlive = compAlive(i.year,i.month,birth.year,birth.month) ? 'a4_alive' : '';
            let isChild = compDate(i.year, i.month, birth.year, birth.month) ? 'a4_child' : '';
            let isSchool = compDate(i.year, i.month, school.year, school.month) ? 'a4_school' : '';
            let isJob = compDate(i.year, i.month, job.year, job.month) ? 'a4_job' : '';

            let isSpec = hasSpec(i,birth, school,job) || '';
            
            html += `<div data-inf="${i.year}.${i.month}" data-spec="${isSpec}" class="a4_item ${isAlive} ${isChild} ${isSchool} ${isJob} ${!!isSpec ? 'a4_spec':''}"></div>`;
        }
        $('.a4_list').html(html);
    }

    function compAlive(...arg){
        // let [ Y, M, y, m ] = arg;
        // const MON = 1000 * 60 * 24 * 30;
        //     CUR = new Date(Y,M).getTime(),
        //     BIR = new Date(y,m).getTime(),
        //     DIE = new Date(y+ AGE,m).getTime();
        // console.log(CUR,BIR,DIE)

        let [ Y, M, y, m ] = arg;
        return (y<Y || (y===Y && m<=M)) && ( Y<(y+AGE) || ((y+AGE)===Y && m>M))
    }

    function compDate(...arg){
        let [Y, M, y, m] = arg;
        return (y < Y || (y === Y && m <= M)) && (Y < new Date().getFullYear() || (new Date().getFullYear() === Y && new Date().getMonth()+1 >= M))
    }

    function hasSpec(...arg){
        let [i,b,s,j] =  arg;
        if (i.year === b.year && i.month === b.month) {
            return `${i.year}年${i.month}月，老子降生了`
        } else if (i.year === s.year && i.month === s.month) {
            return `${i.year}年${i.month}月，我上小学了`
        } else if (i.year === j.year && i.month === j.month) {
            return `${i.year}年${i.month}月，正式接受社会毒打`
        } else if (i.year === (b.year + 70) && i.month === b.month) {
            return `${i.year}年${i.month}月，古稀之年，是时候退休了`
        // } else if (i.year === (b.year + 65) && i.month === b.month) {
        //     return `65岁，顽疾缠身`
        } else if (i.year === (b.year + AGE) && i.month === b.month ) {
            return `${i.year}年${i.month}月，仙逝`
        }
    }

    const motto = [
        "每一个不曾起舞的日子，都是对生命的辜负",
        "用尽了全力，过着平凡的一生",
        "人生的剧本，不是你父母的续集，不是你子女的前传，更不是你朋友的外篇",
        "宣父犹能畏后生,丈夫未可轻年少",
    ]

    $('.export').click(function(){
        hideF();
        html2canvas($('.a4_cont')[0]).then(canvas => {
            $('#export').html(canvas);
            // console.log(canvas)
            layer.open({
                type: 1,
                title: '导出',
                shadeClose: true,
                area: '1200px',
                content: $('#export') ,
                btn: ['导出PNG'],
                yes: function (index, layero) {
                    // console.log(layero)
                    download(canvas.toDataURL("image/png"));
                    showF();
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                },
                end: function(){
                    showF();
                }
            });
        });
    })

    function hideF(){
        // var { cut,res } = trip((new Date().getFullYear() - a4.birth.year) / AGE),
        //     res = `旅途已${cut>0?'超过':'接近'}`;
        var j = Math.floor(Math.random() * (motto.length));
        $('.a4_desc').html(motto[j]);
        $('.a4_nav_right').hide();
        $('.a4_desc').show();
    }
    function showF(){
        $('.a4_nav_right').show();
        $('.a4_desc').hide();
    }

    function trip(t){
        const arr = [0, 1 / 3, 1 / 2, 2 / 3, 1];
        var cut = 1, res = 0;
        arr.forEach((item, i) => {
            if (Math.abs(item - t) < cut) {
                cut = t - item;
                res = i;
            }
        })
        return {cut, res};
    }

    function download(base64){
        var a = document.createElement("a");
        a.download = 'A4'　　//下载的文件名，默认是'下载'
        a.href = base64;
        document.body.appendChild(a); 
        a.click(); 
        a.remove();
    }
    
})

    

</script>
</body>
</html>